import {Component, OnInit} from '@angular/core';
import {ManageService} from '../manage.service';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-image-category',
  templateUrl: './image-category.component.html',
  styleUrls: ['./image-category.component.scss']
})
export class ImageCategoryComponent implements OnInit {
  listOfData: any = {
    current: 1,
    total: 0,
    size: 20,
    records: []
  };
  checked = false;
  indeterminate = false;
  modal: any = {
    modalVisible: false,
    isAdd: true,
  };
  form: any = {
    id: null,
    name: null,
    status: 1,
  };

  constructor(
    private manageService: ManageService,
    private msg: NzMessageService
  ) {
  }

  ngOnInit(): void {
    this.queryTableList();
  }

  /**
   * page number 必须 分页
   * pageSize number 必须 分页大小
   */
  queryTableList() {
    this.listOfData.records = [];
    this.manageService.httpPost(this.manageService.serviceUrl.imgCategory,
      {
        page: this.listOfData.current,
        pageSize: this.listOfData.size,
      }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData.records = res.data.records;
        this.listOfData.total = res.data.total;
      }
    });
  }

  onPageIndexChange(index: number) {
    console.log(index);
    this.listOfData.current = index;
    this.queryTableList();
  }

  onPageSizeChange(size: number) {
    this.listOfData.size = size;
    this.queryTableList();
  }


  appendCategory() {
    console.log('添加分类');
    this.modal.modalVisible = true;
    this.modal.isAdd = true;
  }

  edit(data: any) {
    console.log(data, '编辑');
    this.form.id = data.id;
    this.form.name = data.name;
    this.form.status = data.status;
    this.modal.modalVisible = true;
    this.modal.isAdd = false;
  }

  // 模态框取消按钮监听
  handleModalCancel() {
    this.modal.modalVisible = false;
    this.resetFormData();
  }

  // 模态框确认按钮监听
  handleModalOk() {
    if (!this.form.name) {
      this.msg.error('请输入名称');
    } else {
      this.manageService.httpPost(this.manageService.serviceUrl.imgCategoryAdd, this.form).then((res: any) => {
        if (res.code === 0) {
          this.modal.modalVisible = false;
          this.resetFormData();
          this.msg.success('添加成功');
        } else {
          this.msg.error(res.message);
        }
      });
    }
  }

  // 重置数据
  resetFormData() {
    this.form = {
      id: null,
      name: null,
      status: 1,
    };
  }

  deleteRow(id: any) {
    console.log('删除行', id);
  }

  changeStatus(data: any) {
    this.changeMultipleStatus([data.id], data.status === 0 ? 1 : 0);
  }

  changeMultipleStatus(ids: string[], status: number) {
    const body = ids.map(id => ({id, status}));
    this.manageService.httpPost(this.manageService.serviceUrl.imgStatus, body).then((res: any) => {
      console.log(res);
      this.msg.success(res.message);
      this.queryTableList();
    });
  }
}
